/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Servlets;

import EntityPackage.BusinessLogic;
import EntityPackage.Cliente;
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author work
 */
public class Login extends HttpServlet {
    @EJB
    private BusinessLogic businessLogic;
    HttpSession session;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            RequestDispatcher rd;
            switch (request.getParameter("hidden")) {
                case "registra":
                    String user = request.getParameter("username");
                    if(businessLogic.usedUsername(user)){
                        // lo user è già utilizzato
                        response.addHeader("errore", "");
                        response.addHeader("nome", request.getParameter("nome"));
                        response.addHeader("cognome", request.getParameter("cognome"));
                        response.addHeader("email", request.getParameter("email"));
                        if(!request.getParameter("indirizzo").isEmpty())
                            response.addHeader("indirizzo", request.getParameter("indirizzo"));        
                        if(!request.getParameter("telefono").isEmpty())
                            response.addHeader("telefono", request.getParameter("telefono"));       
                        rd = getServletContext().getRequestDispatcher("/registrati.jsp");
                        rd.forward(request, response);
                    //    response.sendRedirect("registrati.jsp");
                    }else{                 
                    Cliente c = new Cliente();
                    c.setNome(request.getParameter("nome"));
                    c.setCognome(request.getParameter("cognome"));
                    c.setEmail(request.getParameter("email"));
                    c.setUsername(user);
                    c.setPassword(request.getParameter("password"));
                    if(!request.getParameter("indirizzo").isEmpty())
                        c.setIndirizzo(request.getParameter("indirizzo"));                 
                    if(!request.getParameter("telefono").isEmpty())
                        c.setIndirizzo(request.getParameter("telefono"));
                    
                    businessLogic.addCliente(c);
                    //Registraz andata a buon fine
                    response.sendRedirect("index.jsp");
                    }
                    break;
                case "login":
                    Cliente cl = businessLogic.verifyClient(request.getParameter("username"), request.getParameter("password"));
                    if(cl == null){
                        session = request.getSession(true);
                        session.setAttribute(("logged"), "false");
                        response.sendRedirect("index.jsp");
                    }else{
                        session = request.getSession(true);
                        session.setAttribute("logged", "true");
                        session.setAttribute("username", request.getParameter("username"));
                        session.setAttribute("name",cl.getNome());
                        session.setAttribute("id", cl.getIdCliente());
                        response.sendRedirect("index.jsp");
                    }
                    break;
                case "face":           
                    session = request.getSession(true);
                    String email = request.getParameter("email");
                    cl = businessLogic.getClienteByMail(email);
                    if(cl == null){                       
                       Cliente c = new Cliente();
                       String nome = request.getParameter("nome");
                       c.setNome(nome.toLowerCase());
                       c.setCognome((request.getParameter("cognome")).toLowerCase());
                       c.setUsername(request.getParameter("username"));
                       c.setEmail(email);
                       businessLogic.addCliente(c);         
                       session.setAttribute("name",nome);    
                       session.setAttribute("id", c.getIdCliente());
                    }else{                    
                        session.setAttribute("name",cl.getNome());   
                        session.setAttribute("id", cl.getIdCliente());}
                    session.setAttribute("logged", "true");                                          
                    break;  
                 case "google":    
                    session = request.getSession(true);
                    email = request.getParameter("email");
                    cl = businessLogic.getClienteByMail(email);
                    if(cl == null){             
                       Cliente c = new Cliente();
                       String nome = (request.getParameter("nome")).toLowerCase();
                       c.setNome(nome);
                       String cognome = (request.getParameter("cognome")).toLowerCase();
                       c.setCognome(cognome);
                       user = "g_"+nome+"."+cognome;
                       c.setUsername(user);
                       c.setEmail(email);
                       businessLogic.addCliente(c);  
                       session.setAttribute("name",nome);      
                       session.setAttribute("id", c.getIdCliente());
                    }else{                    
                        session.setAttribute("name",cl.getNome());   
                        session.setAttribute("id", cl.getIdCliente());}
                    session.setAttribute("logged", "true");                    
                    break; 
                 case "logout":
                    session = request.getSession();
                    session.invalidate();
                    response.sendRedirect("index.jsp");
                    break;
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
